package com.gwt.tirso.gymkhana.client;

import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwt.tirso.gymkhana.shared.DelistedException;

public class CreationStep4 implements EntryPoint {

	private Label finalize = new Label();
	private Label pass = new Label();
	private Label note = new Label();
	private Label errorLabel = new Label();
	private TextBox pass1 = new PasswordTextBox();
	private TextBox pass2 = new PasswordTextBox();
	private VerticalPanel mainPanel = new VerticalPanel();
	private HorizontalPanel buttonsPanel = new HorizontalPanel();
	private Button accept = new Button();
	private Button cancel = new Button();
	private Gymkhana gymk;
	private List<Question> lq;

	private IGymkhanaServiceAsync gymCon;
	private ILoginServiceAsync loginCon;
	private Person author;
	

	public void setGymk(Gymkhana gymk) {
		this.gymk = gymk;
	}

	public void setLq(List<Question> lq) {
		this.lq = lq;
	}

	@Override
	public void onModuleLoad() {
		
		loadCreationStep4();
		
	}

	private void loadCreationStep4() {
		// Labels
		finalize.setText("Ultimo paso");
		pass.setText("Password");
		note.setText("Al pulsar finalizar habra terminado de configurar su Gymkhana\nPara obtener los codigos de las preguntas podra acceder siempre que quiera desde su perfil");

		// Buttons
		accept.setText("Finalizar");
		cancel.setText("Cancelar");

		// mainPanel
		mainPanel.add(finalize);
		mainPanel.add(pass);
		mainPanel.add(pass1);
		mainPanel.add(pass2);
		mainPanel.add(note);

		buttonsPanel.add(accept);
		buttonsPanel.add(cancel);

		mainPanel.add(buttonsPanel);

		// initialize connections
		gymCon = ConnectionRpc.initRpcGymkhana();
		loginCon = ConnectionRpc.initRpcLogin();

		accept.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				
				loginCon.loginFromSessionServer(new AsyncCallback<Person>() {

					@Override
					public void onSuccess(Person result) {
						if (result == null) {
							Window.alert("Para acceder a la aplicación debe iniciar sesión");
							cancelStep();
						} else {
							receiveInfo();
							if (gymk.getPass() == null) {
								mainPanel.add(errorLabel);
							} else {
								
								AsyncCallback<Gymkhana> callback = new AsyncCallback<Gymkhana>() {

									@Override
									public void onFailure(Throwable caught) {

										String details = caught.getMessage();
								        if (caught instanceof DelistedException) {
								          details = "Company '" + ((DelistedException)caught).getSymbol() + "' was delisted";
								        }

								        errorLabel.setText("Error: " + details);
								        errorLabel.setVisible(true);
									}

									@Override
									public void onSuccess(Gymkhana result) {
										
										
										// finalize the creationManager
										nextStep();
									}
								};
								AsyncCallback<Question> callbackQ = new AsyncCallback<Question>() {

									@Override
									public void onFailure(Throwable caught) {
										// TODO Auto-generated method stub
										
									}

									@Override
									public void onSuccess(Question result) {
										// TODO Auto-generated method stub
										
									}
								};

								// Here, we insert the Gymkhana and the questions with
								// our
								// manager
								
								
								//gymk.setQuestionList(lq);
								
								for(Question q: lq){
									gymCon.insertQuestion(q, callbackQ);
									gymk.addQuestion(q);
								}
								gymCon.createGymkhana(gymk, callback);
								
							}
						}

					}

					@Override
					public void onFailure(Throwable caught) {
						String details = caught.getMessage();
				        if (caught instanceof DelistedException) {
				          details = "Company '" + ((DelistedException)caught).getSymbol() + "' was delisted";
				        }

				        errorLabel.setText("Error: " + details);
				        errorLabel.setVisible(true);

					}
				});
			}
		});

		cancel.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {

				cancelStep();

			}
		});
		
		errorLabel.addStyleName("errorLabel");
		mainPanel.addStyleName("creationNext");
		RootPanel.get("creation").add(mainPanel);
		
	}

	protected void nextStep() {
		GymkhanaWeb gw = new GymkhanaWeb();
		gw.onModuleLoad();
		RootPanel.get("creation").remove(mainPanel);
	}

	public void receiveInfo() {
		String s1 = pass1.getText();
		String s2 = pass2.getText();

		if (s1 == null || s2 == null) {
			errorLabel.setText("Introduzca una contraseña");
			return;
		} else if (s1.equals(s2) == false) {
			errorLabel
					.setText("Escriba la misma contraseña en ambos cuadros de texto");
			return;
		} else if (s1.length() < 4 || s1.length() > 8) {
			errorLabel
					.setText("La contraseña tiene que tener entre 4 y 8 caracteres");
			return;
		} else {
			
			gymk.setPass(s1);
			
		}
	}

	private void cancelStep() {
		GymkhanaWeb gw = new GymkhanaWeb();
		gw.onModuleLoad();
		RootPanel.get("creation").remove(mainPanel);
	}

	public void setAuthor(Person author) {
		this.author = author;
	}
}
